package com.zx.mes.hyl.zuul.controller;

import com.zx.mes.hyl.response.ObjectRestResponse;
import com.zx.mes.hyl.zuul.constant.CredentialType;
import com.zx.mes.hyl.zuul.feign.Oauth2Client;
import com.zx.mes.hyl.zuul.pagemodel.SystemClientInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


/**
 * 登录获取token
 *
 * @author 华云龙
 * @date 2018-12-17
 */
@Slf4j
@RestController
@RequestMapping("/api/token")
public class LoginController {

    @Autowired
    private Oauth2Client oauth2Client;

    /**
     * 系统登陆<br>
     * 根据用户名登录<br>
     * 采用oauth2密码模式获取access_token和refresh_token
     *
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/login")
    public ObjectRestResponse<Map<String, Object>> login(String username, String password) {
        Map<String, String> parameters = new HashMap<>(8);
        parameters.put(OAuth2Utils.GRANT_TYPE, "password");
        parameters.put(OAuth2Utils.CLIENT_ID, SystemClientInfo.CLIENT_ID);
        parameters.put("client_secret", SystemClientInfo.CLIENT_SECRET);
        parameters.put(OAuth2Utils.SCOPE, SystemClientInfo.CLIENT_SCOPE);

        /// 为了支持多类型登录，这里在username后拼装上登录类型
        parameters.put("username", username + "|" + CredentialType.USERNAME.name());
        parameters.put("password", password);

        Map<String, Object> tokenInfo = oauth2Client.postAccessToken(parameters);
        tokenInfo.put("username", username);

        ObjectRestResponse.Builder<Map<String, Object>> response = new ObjectRestResponse.Builder<>();
        response.message("token获取成功!").status(200).data(tokenInfo);


        log.debug("登录后,返回信息:" + tokenInfo);
        return response.build();
    }
}
